<?php
App::uses('AppController', 'Controller');
class UserController extends AppController
{
    public $name = 'User';
    public $uses = array(
        'Account',
        'UserChar',
        'UserCharStat',
        'UserCharFriend',
        'UserCharItem',
        'UserCharAcc',
        'UserCharSkill',
        'UserCharLeaderSkill',
        'UserCharMaterial',
        'UserCharMonster',
        'UserCharGroup',
        'UserCharFarm',
        'UserCharFarmField',
        'UserCharFarmThief',
        'UserCharFriend',
        'UserCharQuest',
        'Notification',
        'StageItem',
        'DailyQuest',
        'DeviceInfo',
        'LogClient',
        'LogCrystal',
        'LogDauData',
        'LogGold',
        'LogServerCount',
        'LogConnect',
        'LogStatsData',
        'LogMcuList',
        'WMapInfoList',
        'W1MapInfoList',
        'W2MapInfoList',
        'W3MapInfoList',
        'W4MapInfoList',
        'W5MapInfoList',
        'MyRedis'
    );

    public function index()
    {
        $header_name = $this->header_name;
        $this->set(compact(array('header_name')));
        if(!empty($this->data))
        {
            if(!empty($this->data['notice']))
            {
                $msg = $this->data['notice']['msg'];
                if(!empty($msg))
                {
                    App::uses('HttpSocket', 'Network/Http');
                    $HttpSocket = new HttpSocket();

                    $url = $this->server_url . '/notice_all';
                    $data = 'msg='.$msg;

                    if(!$HttpSocket->post($url, $data))
                    {
                        return 'error!!!';
                    }

                    $this->Session->setFlash('공지 전송 완료', 'default', array('class' => 'success'), 'good');
                }
            }
            else if(!empty($this->data['stage']))
            {
                $this->UserChar->id = $this->data['stage']['char_id'];
                $data['stage_clear'] = $this->data['stage']['stage_clear'];

                if($this->UserChar->stage_save($this->db_name, $this->data['stage']['char_id'], $this->data['stage']['stage_clear']))
                {
                    $this->Session->setFlash('스테이지 변경 완료', 'default', array('class' => 'success'), 'good');
                }
                else
                {
                    $this->Session->setFlash('스테이지 변경 실패', 'default', array('class' => 'message'), 'bad');
                }
            }
            else if(!empty($this->data['char_del']))
            {
                if($this->data)
                {
                    App::uses('HttpSocket', 'Network/Http');
                    $HttpSocket = new HttpSocket();

                    $url = $this->server_url . '/user_char_del';
                    $data = 'auth_token=auth_token&usn='.$this->data['char_del']['usn'].'&char_id='.$this->data['char_del']['char_id'];

                    if(!$HttpSocket->post($url, $data))
                    {
                        return 'error!!!';
                    }
                }
            }
            else if(!empty($this->data['level']))
            {
                if($this->data)
                {
                    App::uses('HttpSocket', 'Network/Http');
                    $HttpSocket = new HttpSocket();

                    $data = 'usn='.$this->data['level']['usn'].'&char_id='.$this->data['level']['char_id'];
                    $url = $this->server_url . '/char_lv_up';

                    if(!$HttpSocket->post($url, $data))
                    {
                        return 'error!!!';
                    }
                }
            }
            else if(!empty($this->data['material']))
            {
                if($this->data)
                {
                    App::uses('HttpSocket', 'Network/Http');
                    $HttpSocket = new HttpSocket();

                    $data = 'usn='.$this->data['material']['usn'].'&char_id='.$this->data['material']['char_id'];

                    $url = $this->server_url . '/all_material';

                    if(!$HttpSocket->post($url, $data))
                    {
                        return 'error!!!';
                    }
                }
            }
            else if(!empty($this->data['skill']))
            {
                if($this->data)
                {
                    App::uses('HttpSocket', 'Network/Http');
                    $HttpSocket = new HttpSocket();

                    $data = 'usn='.$this->data['skill']['usn'].'&char_id='.$this->data['skill']['char_id'];

                    $url = $this->server_url . '/all_skill';

                    if(!$HttpSocket->post($url, $data))
                    {
                        return 'error!!!';
                    }
                }
            }
            else if(!empty($this->data['monster']))
            {
                if($this->data)
                {
                    App::uses('HttpSocket', 'Network/Http');
                    $HttpSocket = new HttpSocket();

                    $data = 'usn='.$this->data['monster']['usn'].'&char_id='.$this->data['monster']['char_id'];

                    $url = $this->server_url . '/all_monster';

                    if(!$HttpSocket->post($url, $data))
                    {
                        return 'error!!!';
                    }
                }
            }
        }





        $account_info = $this->Account->get_account_all($this->db_name);
        foreach($account_info as $num => $account_data)
        {
            $char_data = $this->UserChar->get_char($this->db_name, $account_data['Account']['_id']);

            foreach($char_data as $char_value)
            {
                $nick_name = $char_value['UserChar']['nick_name'];
                $account_info[$num]['Account']['nick_name'][$nick_name] = $char_value['UserChar']['_id'];
                $account_info[$num]['Account']['char_id'] = $char_value['UserChar']['_id'];
                $account_info[$num]['Account']['stage_clear'] = $char_value['UserChar']['stage_clear'];
                //pr($char_value['UserChar']['stage_clear']);
                    //empty($char_value['UserChar']['stage_clear']) ? '1_0' : $char_value['UserChar']['stage_clear'];
                $account_info[$num]['Account']['level'] = $char_value['UserChar']['level'];
            }

            $connect_log = $this->LogConnect->get_connect_log($this->db_name, $account_data['Account']['_id']);
//            if(!empty($connect_log))
//                $account_info[$num]['Account']['connect_count'] = $connect_log['LogConnect']['count'];
//            else
//                $account_info[$num]['Account']['connect_count'] = 0;
        }


        $map1_data = $this->W1MapInfoList->get_map_id($this->db_name);
        $map2_data = $this->W2MapInfoList->get_map_id($this->db_name);
        $map3_data = $this->W3MapInfoList->get_map_id($this->db_name);
        $map4_data = $this->W4MapInfoList->get_map_id($this->db_name);
        $map5_data = $this->W5MapInfoList->get_map_id($this->db_name);

        foreach($map1_data as $stage)
        {
            $stage_option['1_1_1_0'] = '없음';
            $stage_option[$stage['W1MapInfoList']['Id']] = $stage['W1MapInfoList']['Id'];
        }

        foreach($map2_data as $stage)
        {
            $stage_option['1_1_1_0'] = '없음';
            $stage_option[$stage['W2MapInfoList']['Id']] = $stage['W2MapInfoList']['Id'];
        }

        foreach($map3_data as $stage)
        {
            $stage_option['1_1_1_0'] = '없음';
            $stage_option[$stage['W3MapInfoList']['Id']] = $stage['W3MapInfoList']['Id'];
        }

        foreach($map4_data as $stage)
        {
            $stage_option['1_1_1_0'] = '없음';
            $stage_option[$stage['W4MapInfoList']['Id']] = $stage['W4MapInfoList']['Id'];
        }

        foreach($map5_data as $stage)
        {
            $stage_option['1_1_1_0'] = '없음';
            $stage_option[$stage['W5MapInfoList']['Id']] = $stage['W5MapInfoList']['Id'];
        }

        /*$stage_average = 0;
        if(count($account_info) != 0)
        {
            $stage_average = round($stage_total / count($account_info), 1);
        }*/

        //$char_average = $this->UserChar->get_avg($this->db_name);

        $header_name = $this->header_name;
        //$this->set(compact(array('account_info', 'header_name', 'stage_option', 'stage_average', 'char_average')));
        $this->set(compact(array('account_info', 'header_name', 'stage_option', 'stage_average', 'char_average')));
    }

    public function server_count()
    {
        $server_count = $this->LogServerCount->get_count($this->db_name);

        if(!empty($server_count))
        {
            foreach($server_count as $num => $data)
            {
                $server[$num]['count'] = $data['LogServerCount']['channel_count'];
                $server[$num]['name'] = $data['LogServerCount']['channel_name'];
            }
        }
        else
        {
            $server[0]['count'] = 0;
            $server[0]['name'] = 'chat_1';
            $server[1]['count'] = 0;
            $server[1]['name'] = 'lobby_1';
        }

        $header_name = $this->header_name;
        $this->set(compact(array('header_name', 'server_count', 'server')));
    }

    public function igs_user()
    {
        $igs_user = $this->UserChar->get_igs_user($this->db_name);

        $header_name = $this->header_name;
        $this->set(compact(array('header_name', 'igs_user')));
    }

    public function stat_list()
    {
        // 레벨별 유저 수
        $user_data = $this->UserChar->get_char_all($this->db_name);

        $user_level = '';
        $item_add = true;

        $user_stage = '';
        $stage_add = true;

        foreach($user_data as $num => $value)
        {
            $user_play_time = $this->LogConnect->get_connect_log($this->db_name, $value['UserChar']['usn']);

            // 레벨 별 인원
            if(is_array($user_level))
            {
                foreach($user_level as $level_num => $level_key)
                {
                    if($level_key['level'] == $value['UserChar']['level'])
                    {
                        $user_level[$level_num]['count'] += 1;
                        $user_level[$level_num]['play_time'] += $user_play_time['LogConnect']['play_time'];
                        $item_add = false;
                        break;
                    }
                    else
                    {
                        $item_add = true;
                    }
                }
            }

            if($item_add == true)
            {
                $user_level[$num]['level'] = $value['UserChar']['level'];
                $user_level[$num]['count'] = 1;
                $user_level[$num]['play_time'] = empty($user_play_time['LogConnect']['play_time']) ? 0 : $user_play_time['LogConnect']['play_time'];
            }

            // 스테이지별 인원
            if(is_array($user_stage))
            {
                foreach($user_stage as $stage_num => $stage_key)
                {
                    if($stage_key['stage'] == $value['UserChar']['stage_clear'])
                    {
                        $user_stage[$stage_num]['count'] += 1;
                        $stage_add = false;
                        break;
                    }
                    else
                    {
                        $stage_add = true;
                    }
                }
            }

            if($stage_add == true)
            {
                $user_stage[$num]['stage'] = $value['UserChar']['stage_clear'];
                $user_stage[$num]['count'] = 1;
            }
        }

        // 레벨 별 플레이 타임
        foreach($user_level as $tmp_num => $tmp_value)
        {
            $user_level[$tmp_num]['play_time'] = round($user_level[$tmp_num]['play_time'] / $user_level[$tmp_num]['count']);
            $hours = floor($user_level[$tmp_num]['play_time'] / 3600);
            $user_level[$tmp_num]['play_time'] = $user_level[$tmp_num]['play_time'] - ($hours * 3600);
            $min = floor($user_level[$tmp_num]['play_time'] / 60);
            $sec = $user_level[$tmp_num]['play_time'] - ($min * 60);

            $user_level[$tmp_num]['time'] = array(
                'hours' => $hours,
                'min' => $min,
                'sec' => $sec
            );
        }

        // 평균 플레이 타임
        $play_time = $this->LogConnect->get_play_time_avg($this->db_name);
        $play_time = round($play_time / count($user_data));
        $hours = floor($play_time / 3600);
        $play_time = $play_time - ($hours * 3600);
        $min = floor($play_time / 60);
        $sec = $play_time - ($min * 60);
        $play_time_array = array(
            'hours' => $hours,
            'min' => $min,
            'sec' => $sec
        );

        // 평균 농장 레벨
        $farm_data = $this->UserCharFarm->get_data($this->db_name);
        $farm_level_total = 0;
        foreach($farm_data as $farm_num => $value)
        {
            $farm_level_total += $value['UserCharFarm']['level'];
        }

        $farm_level_avg = round($farm_level_total / count($user_data), 0);

        // 진화, 성장, 도움, 약탈, 수확, 아이템 업 통계
        $stats_data = $this->LogStatsData->get_data($this->db_name);

        $monster_evolve = 0;
        $monster_grow = 0;
        $item_upgrade = 0;
        $farm_thief = 0;
        $farm_help = 0;
        $farm_harvest = 0;

        foreach($stats_data as $stats_num => $value)
        {
            $monster_evolve += $value['LogStatsData']['monster_evolve'];
            $monster_grow += $value['LogStatsData']['monster_grow'];
            $item_upgrade += $value['LogStatsData']['item_upgrade'];
            $farm_thief += $value['LogStatsData']['farm_thief'];
            $farm_help += $value['LogStatsData']['farm_help'];
            $farm_harvest += $value['LogStatsData']['farm_harvest'];
        }

        $stats = array(
            'monster_evolve' => $monster_evolve,
            'monster_grow' => $monster_grow,
            'item_upgrade' => $item_upgrade,
            'farm_thief' => $farm_thief,
            'farm_help' => $farm_help,
            'farm_harvest' => $farm_harvest
        );

        // 골드 획득, 사용 통계
        $gold_data = $this->LogGold->get_data($this->db_name);

        $gole_log = '';
        $item_add = true;
        foreach($gold_data as $gold_num => $value)
        {
            if(is_array($gole_log))
            {
                foreach($gole_log as $tmp_num => $key)
                {
                    if($key['type'] == $value['LogGold']['type'])
                    {
                        $gole_log[$tmp_num]['count'] += 1;
                        $gole_log[$tmp_num]['gold'] += $value['LogGold']['gold'];
                        $item_add = false;
                        break;
                    }
                    else
                    {
                        $item_add = true;
                    }
                }
            }

            if($item_add == true)
            {
                $gole_log[$gold_num]['type'] = $value['LogGold']['type'];
                $gole_log[$gold_num]['count'] = 1;
                $gole_log[$gold_num]['gold'] = $value['LogGold']['gold'];
            }
        }

        // 크리스탈 획득, 사용 통계
        $crystal_data = $this->LogCrystal->get_data($this->db_name);

        $crystal_log = '';
        $item_add = true;
        foreach($crystal_data as $crystal_num => $value)
        {
            if(is_array($crystal_log))
            {
                foreach($crystal_log as $tmp_num => $key)
                {
                    if($key['type'] == $value['LogCrystal']['type'])
                    {
                        $crystal_log[$tmp_num]['count'] += 1;
                        $crystal_log[$tmp_num]['crystal'] += $value['LogCrystal']['crystal'];
                        $item_add = false;
                        break;
                    }
                    else
                    {
                        $item_add = true;
                    }
                }
            }

            if($item_add == true)
            {
                $crystal_log[$crystal_num]['type'] = $value['LogCrystal']['type'];
                $crystal_log[$crystal_num]['count'] = 1;
                $crystal_log[$crystal_num]['crystal'] = $value['LogCrystal']['crystal'];
            }
        }

        // 리텐션
        $test_one_day = array();
        $test_two_day = array();

        for($a = 20; $a <= 22; ++$a)
        {
            $test_nur = 0;
            $r_start_date = mktime(13,0,0,8,$a,2014);
            $r_end_date = mktime(18,0,0,8,$a,2014);

            $one_start_date = mktime(13,0,0,8,($a-1),2014);
            $one_end_date = mktime(18,0,0,8,($a-1),2014);

            $two_start_date = mktime(13,0,0,8,($a-2),2014);
            $two_end_date = mktime(18,0,0,8,($a-2),2014);

            foreach($user_data as $user_num => $user_value)
            {
                // nru
                if($r_start_date <= mongoDateToTime($user_value['UserChar']['created'], false) &&
                    $r_end_date > mongoDateToTime($user_value['UserChar']['created'], false))
                {
                    $test_nur++;
                }

                // 1day
                if($one_start_date <= mongoDateToTime($user_value['UserChar']['created'], false) &&
                    $one_end_date > mongoDateToTime($user_value['UserChar']['created'], false))
                {
                    if($r_start_date <= mongoDateToTime($user_value['UserChar']['modified'], false) &&
                        $r_end_date > mongoDateToTime($user_value['UserChar']['modified'], false))
                    {
                        $test_one_day[] = $user_value;
                    }
                }

                // 2day
                if($two_start_date <= mongoDateToTime($user_value['UserChar']['created'], false) &&
                    $two_end_date > mongoDateToTime($user_value['UserChar']['created'], false))
                {
                    if($r_start_date <= mongoDateToTime($user_value['UserChar']['modified'], false) &&
                        $r_end_date > mongoDateToTime($user_value['UserChar']['modified'], false))
                    {
                        $test_two_day[] = $user_value;
                    }
                }

            }

            $dau = $this->LogDauData->get_dau($this->db_name, $a);

            $test_re[$a]['nru'] = $test_nur;
            $test_re[$a]['dau'] = empty($dau['LogDauData']['count']) ? 0 : $dau['LogDauData']['count'];
            $test_re[$a]['1day'] = count($test_one_day);
            $test_re[$a]['2day'] = count($test_two_day);
        }

        $test_one_user_level = '';
        $test_one_item_add = true;
        foreach($test_one_day as $test_one_num => $test_one_value)
        {
            // 레벨 별 인원
            if(is_array($test_one_user_level))
            {
                foreach($test_one_user_level as $level_one_num => $level_one_key)
                {
                    if($level_one_key['level'] == $test_one_value['UserChar']['level'])
                    {
                        $test_one_user_level[$level_one_num]['count'] += 1;
                        $test_one_item_add = false;
                        break;
                    }
                    else
                    {
                        $test_one_item_add = true;
                    }
                }
            }

            if($test_one_item_add == true)
            {
                $test_one_user_level[$test_one_num]['level'] = $test_one_value['UserChar']['level'];
                $test_one_user_level[$test_one_num]['count'] = 1;
            }
        }


        $test_two_user_level = '';
        $test_two_item_add = true;
        foreach($test_two_day as $test_two_num => $test_two_value)
        {
            // 레벨 별 인원
            if(is_array($test_two_user_level))
            {
                foreach($test_two_user_level as $level_two_num => $level_two_key)
                {
                    if($level_two_key['level'] == $test_two_value['UserChar']['level'])
                    {
                        $test_two_user_level[$level_two_num]['count'] += 1;
                        $test_two_item_add = false;
                        break;
                    }
                    else
                    {
                        $test_two_item_add = true;
                    }
                }
            }

            if($test_two_item_add == true)
            {
                $test_two_user_level[$test_two_num]['level'] = $test_two_value['UserChar']['level'];
                $test_two_user_level[$test_two_num]['count'] = 1;
            }
        }

        $header_name = $this->header_name;
        $this->set(compact(array('header_name', 'muc_list', 'stats', 'gole_log', 'crystal_log',
            'user_level', 'user_stage', 'play_time_array', 'farm_level_avg',
            'test_re', 'test_one_user_level', 'test_two_user_level'
        )));
    }

    public function mcu_list()
    {
        $get_mcu_list = $this->LogMcuList->get_mcu_list($this->db_name);
        foreach($get_mcu_list as $num => $data)
        {
            $muc_list[$num]['created'] = mongoDateToTime($data['LogMcuList']['created']);
            $muc_list[$num]['count'] = $data['LogMcuList']['count'];
        }

        $header_name = $this->header_name;
        $this->set(compact(array('header_name', 'muc_list')));
    }

    public function delete_all()
    {
        if ($this->Account->delect_all($this->db_name))
        {
            $this->UserChar->delect_all($this->db_name);
            $this->UserCharStat->delect_all($this->db_name);
            $this->UserCharFriend->delect_all($this->db_name);
            $this->UserCharItem->delect_all($this->db_name);
            $this->UserCharAcc->delect_all($this->db_name);
            $this->UserCharSkill->delect_all($this->db_name);
            $this->UserCharLeaderSkill->delect_all($this->db_name);
            $this->UserCharMaterial->delect_all($this->db_name);
            $this->UserCharMonster->delect_all($this->db_name);
            $this->UserCharGroup->delect_all($this->db_name);
            $this->UserCharFarm->delect_all($this->db_name);
            $this->UserCharFarmField->delect_all($this->db_name);
            $this->UserCharFarmThief->delect_all($this->db_name);
            $this->UserCharQuest->delect_all($this->db_name);
            $this->Notification->delect_all($this->db_name);
            $this->StageItem->delect_all($this->db_name);
            $this->DailyQuest->delect_all($this->db_name);
            $this->DeviceInfo->delect_all($this->db_name);
            $this->LogClient->delect_all($this->db_name);
            $this->LogConnect->delect_all($this->db_name);
            $this->LogCrystal->delect_all($this->db_name);
            $this->LogDauData->delect_all($this->db_name);
            $this->LogGold->delect_all($this->db_name);
            $this->LogServerCount->delect_all($this->db_name);
            $this->LogStatsData->delect_all($this->db_name);

            $this->Session->setFlash('디비 초기화 완료', 'default', array('class' => 'success'), 'good');
            $this->redirect(array('action' => 'index', $this->passedArgs[0]));
        }

        $this->Session->setFlash('디비 초기화 실패', 'default', array('class' => 'message'), 'bad');
        $this->redirect(array('action' => 'index', $this->passedArgs[0]));
    }

    /*public function account_del()
    {
        if ($this->Account->account_del($this->db_name, $this->passedArgs['usn']))
        {
            $this->UserChar->char_del_all($this->db_name, $this->passedArgs['usn']);
            $this->UserCharStat->char_del_all($this->db_name, $this->passedArgs['usn']);
            $this->UserCharFriend->char_del_all($this->db_name, $this->passedArgs['usn']);
            $this->UserCharItem->char_del_all($this->db_name, $this->passedArgs['usn']);
            $this->UserCharAcc->char_del_all($this->db_name, $this->passedArgs['usn']);
            $this->UserCharSkill->char_del_all($this->db_name, $this->passedArgs['usn']);
            $this->UserCharLeaderSkill->char_del_all($this->db_name, $this->passedArgs['usn']);
            $this->UserCharMaterial->char_del_all($this->db_name, $this->passedArgs['usn']);
            $this->UserCharMonster->char_del_all($this->db_name, $this->passedArgs['usn']);
            $this->UserCharGroup->char_del_all($this->db_name, $this->passedArgs['usn']);
            $this->UserCharFarm->char_del_all($this->db_name, $this->passedArgs['usn']);
            $this->UserCharFarmField->char_del_all($this->db_name, $this->passedArgs['usn']);
            $this->UserCharFarmThief->char_del_all($this->db_name, $this->passedArgs['usn']);
            $this->UserCharQuest->char_del_all($this->db_name, $this->passedArgs['usn']);
            $this->Notification->char_del_all($this->db_name, $this->passedArgs['usn']);
            $this->StageItem->char_del_all($this->db_name, $this->passedArgs['usn']);
            $this->DeviceInfo->char_del_all($this->db_name, $this->passedArgs['usn']);
            $this->LogConnect->char_del_all($this->db_name, $this->passedArgs['usn']);
            $this->LogStatsData->char_del_all($this->db_name, $this->passedArgs['usn']);
            $this->LogClient->char_del_all($this->db_name, $this->passedArgs['usn']);

            $this->Session->setFlash('계정 삭제 완료', 'default', array('class' => 'success'), 'good');
            $this->redirect(array('action' => 'index', $this->passedArgs[0]));
        }

        $this->Session->setFlash('계정 삭제 실패', 'default', array('class' => 'message'), 'bad');
        $this->redirect(array('action' => 'index', $this->passedArgs[0]));
    }*/

    public function char_del()
    {
        if($this->passedArgs)
        {
            App::uses('HttpSocket', 'Network/Http');
            $HttpSocket = new HttpSocket();

            $url = $this->server_url . '/user_char_del';
            $data = 'usn='.$this->passedArgs['usn'].'&char_id='.$this->passedArgs['char_id'];

            if(!$HttpSocket->post($url, $data))
            {
                return 'error!!!';
            }

            $this->Session->setFlash('캐릭터 삭제 완료', 'default', array('class' => 'success'), 'good');
            $this->redirect(array('action' => 'index', $this->passedArgs[0]));
        }
        else
        {
            $this->Session->setFlash('캐릭터 삭제 실패', 'default', array('class' => 'message'), 'bad');
            $this->redirect(array('action' => 'index', $this->passedArgs[0]));
        }
    }

    public function char_level_up()
    {

    }
}